export default {
  data () {
    return {
      // 用户列表
      users: [],
      pagenum: 1,
      pagesize: 4,
      total: 1,
      searchText: '',
      // 添加用户弹窗
      isAddUserForm: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      formLabelWidth: '80px',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '邮箱格式错误', trigger: 'blur' }
        ],
        mobile: [
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号格式错误', trigger: 'blur' }
        ]
      },
      // 编辑用户弹窗
      isShowEditUserForm: false,
      editUserForm: {
        id: -1,
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色数据（角色列表）
      isShowAllotRolesDialog: false,
      rolesListForm: {
        username: '',
        id: 0,
        rid: 0
      },
      // options的数据
      rolesList: []
    }
  },
  methods: {
    // 点击分页
    curChange (cur) {
      this.getUsers(cur, this.searchText)
    },
    // 封装获取用户列表的方法
    async getUsers (pagenum = 1, query = '') {
      const res = await this.axios.get('users', {
        params: {
          query: query,
          pagenum: pagenum,
          pagesize: this.pagesize
        }
      })
      if (res.data.meta.status !== 200) {
        localStorage.removeItem('token')
        this.$router.push('/login')
        return
      }
      const { data: { data: { pagenum: curP, total, users } } } = res
      this.users = users
      this.total = total
      this.pagenum = curP
    },
    // 搜索用户
    searchUsers () {
      this.getUsers(1, this.searchText)
    },
    // 改变用户状态
    async changeUserStatus ({ row: { id, mg_state: state } }) {
      const res = await this.axios.put(`/users/${id}/state/${state}`)
      let { data: { meta: { msg, status } } } = res
      if (status !== 200) return
      if (state) {
        msg = '启用成功'
      } else {
        msg = '禁用成功'
      }
      this.$message({
        message: msg,
        type: 'success'
      })
    },
    // 删除单个用户
    async delUser ({ row: { id } }) {
      try {
        await this.$confirm('你确定删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await this.axios.delete(`/users/${id}`)
        const { data: { meta: { msg, status } } } = res
        if (status !== 200) return
        this.$message({
          message: msg,
          type: 'success'
        })
        this.getUsers(this.pagenum, this.searchText)
      } catch (e) {
        this.$message({
          message: '取消删除'
        })
      }
    },
    // 添加用户 --------------------------
    async addUser () {
      try {
        await this.$refs.addUserForm.validate()
        const res = await this.axios.post('/users/', this.addUserForm)
        const { data: { meta: { msg, status } } } = res
        if (status === 201) {
          this.$message({
            message: msg,
            type: 'success',
            duration: 2000
          })
          this.isAddUserForm = false
        } else {
          this.$message({
            message: msg,
            type: 'error',
            duration: 2000
          })
        }
      } catch (e) { }
    },
    // addUserForm关闭时触发
    addUserFormClose () {
      this.$refs.addUserForm.resetFields()
      this.getUsers(this.pagenum, this.searchText)
    },
    // 编辑用户信息 --------------------------
    // 展示编辑用户form
    showEditUser (scope) {
      this.isShowEditUserForm = true
      for (let key in this.editUserForm) {
        this.editUserForm[key] = scope.row[key]
      }
    },
    // 编辑用户提交
    async editUser () {
      try {
        await this.$refs.editForm.validate()
        const res = await this.axios.put(`users/${this.editUserForm.id}`, this.editUserForm)
        const { data: { meta: { msg, status } } } = res
        if (status === 200) {
          this.$message({
            message: msg,
            type: 'success',
            duration: 2000
          })
          this.isShowEditUserForm = false
        } else {
          this.$message({
            message: msg,
            type: 'error',
            duration: 2000
          })
        }
      } catch (e) { }
    },
    // 编辑用户对话框关闭触发
    editUserFormClose () {
      this.$refs.editForm.resetFields()
      this.getUsers(this.pagenum, this.searchText)
    },
    // 分配角色 --------------------------
    // 点击按钮显示角色列表对话框
    async showRolesList (row) {
      this.isShowAllotRolesDialog = true
      this.rolesListForm.username = row.username
      const res = await this.axios.get(`users/${row.id}`)
      const { data: { data: { id, rid }, meta: { status } } } = res
      console.log(res)
      if (status === 200) {
        this.rolesListForm.id = id
        rid === -1 ? this.rolesListForm.rid = '' : this.rolesListForm.rid = rid
      }
    },
    async userAllotRoles () {
      const res = await this.axios.put(`users/${this.rolesListForm.id}/role`, {
        rid: this.rolesListForm.rid
      })
      const { data: { meta: { msg, status } } } = res
      if (status === 200) {
        this.$message({
          type: 'success',
          message: msg
        })
        this.isShowAllotRolesDialog = false
      } else {
        this.$message({
          type: 'error',
          message: msg
        })
      }
    }
  },
  async created () {
    console.log(this.$route)
    this.getUsers()
    // 获取角色列表
    try {
      const res = await this.axios.get('roles')
      const { data: { data, meta: { status } } } = res
      if (status === 200) {
        this.rolesList = data
      }
    } catch (e) {}
  }
}
